package com.itcs.rongyun.utils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import me.chanjar.weixin.common.exception.WxErrorException;
public class Sms {

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAIeUK71iGlunD0";
    static final String accessKeySecret = "deLdNTyuEoEHuXLXkQABixuTodvAGs";

    private static Log logger = LogFactory.getLog(Sms.class);
    /**
     * 信息变更验证码
     * @param mobile
     * @param code
     * @return 验证码${code}，您正在尝试变更${product}重要信息，请妥善保管账户信息。
     */
    public static SendSmsResponse sendInfoUpdate(String mobile, String code)  {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("ITC");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_122120221");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("ITC");

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return sendSmsResponse;
    }


    /**
     * 收费站通行费扣款通知
     * 支付成功通知，车牌${plate}于${time}在${tollname}支付${amount}元，余额${balance}元；感谢您使用ITC，祝您一路平安！
     * @param mobile    手机号
     * @param plate     车牌号
     * @param time      时间 05月20日13时14分
     * @param tollname  收费站
     * @param amount    支付金额
     * @param balance   账户余额
     * @return
     */
    public static SendSmsResponse payTollNotice(String mobile, String plate,String time,String tollname,String amount,String balance)  {

    	logger.info("收费站通行费扣款短信通知:[mobile=" + mobile + ",plate=" + plate + ",time=" + time + ",tollname=" + tollname + ",amount=" + amount + ",balance=***]");
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("ITC");
        //必填:短信模板-可在短信控制台中找到
//        request.setTemplateCode("SMS_134319663");// 带余额模板
        request.setTemplateCode("SMS_136170388");// 不带余额模板
        //可选:模板中的变量替换JSON串,如模板内容为支付成功通知，车牌${plate}于${time}在${tollname}支付${amount}元，余额${balance}元；感谢您使用ITC，祝您一路平安！时,此处的值为
        request.setTemplateParam("{\"plate\":\"" + plate + "\",\"time\":\""+time+"\",\"tollname\":\""+tollname+"\",\"amount\":\""+amount+"\"}");
//        request.setTemplateParam("{\"plate\":\"" + plate + "\",\"time\":\""+time+"\",\"tollname\":\""+tollname+"\",\"amount\":\""+amount+"\",\"balance\":\""+balance+"\"}");

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("ITC");

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return sendSmsResponse;
    }



    /**
     * 车辆进入高速收费站通知
     * 车牌${plate}于${time}已进入${tollname}，感谢您使用ITC，祝您一路平安！
     * @param mobile    手机号
     * @param plate     车牌号
     * @param time      时间 05月20日13时14分
     * @param tollname  收费站
     * @return
     */
    public static SendSmsResponse inTollNotice(String mobile, String plate,String time,String tollname)  {

    	logger.info("车辆进入高速收费站短信通知：[mobile=" + mobile + ",plate=" + plate + ",time=" + time + ",tollname=" + tollname + "]");
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("ITC");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_134319663");
        //可选:模板中的变量替换JSON串,如模板内容为 车牌${plate}于${time}已进入${tollname}，感谢您使用ITC，祝您一路平安！ 时,此处的值为
        request.setTemplateParam("{\"plate\":\"" + plate + "\",\"time\":\""+time+"\",\"tollname\":\""+tollname+"\"}");

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("ITC");

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return sendSmsResponse;
    }


    public static QuerySendDetailsResponse querySendDetails(String mobile,String bizId) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(mobile);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    /**
     * 发送小程序推送
     * @return
     */
    public static String sendMiniAPPMsg(JSONObject obj) {
    	logger.info("发送小程序短信通知：[" + obj.toJSONString() + "]");
    	  //通过用户ID查找openid
        /**
         * 判断登录方式 如果是为小程序
         * 取 userCustomerInfo.getDeviceAppNo() 字段为 openid
         */
//        String openid = "o6PwI404hK9Rev-v4Ll_naY-OWWs";
        //表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 wxfromid
        //在用户的出口白名单中获取 wxfromid 字段。 如果wxfromid不为空 则发起支付通知
//        String wxfromid = "";

    	String openid = obj.getString("openid");
    	String wxfromid = obj.getString("wxfromid");
    	String carplate = obj.getString("carplate");
    	String tollfee = obj.getString("tollfee");
    	String paystate = obj.getString("paystate");
    	String transeq = obj.getString("transeq");
    	String stationname = obj.getString("stationname");

        //所需下发的模板消息的id
        /**
         * 订单支付成功通知
         * 关键词
	         车牌号 {{keyword1.DATA}} 支付金额 {{keyword2.DATA}} 订单状态 {{keyword3.DATA}}
	
	         订单编号 {{keyword4.DATA}} 服务名称 {{keyword5.DATA}} 温馨提示 {{keyword6.DATA}}
         */
        String WX_MINI_NOTICE_PAY= "6IZjRTPSNAhyPEqftJcRCWRwPlfubjnoz6YjQkpo7DE";
        String templateId = WX_MINI_NOTICE_PAY;
        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        String page ="pages/index/index";
        //模板内容字体的颜色，不填默认黑色
        String color = "";
        String emphasis_keyword = ""; //模板需要放大的关键词，不填则默认无放大

        WxMaTemplateMessage wxMaTemplateMessage = new WxMaTemplateMessage();
        List<WxMaTemplateMessage.Data> tempData = new ArrayList<WxMaTemplateMessage.Data>();

        tempData.add(new WxMaTemplateMessage.Data("keyword1",carplate));
        tempData.add(new WxMaTemplateMessage.Data("keyword2",tollfee + " 元"));
        tempData.add(new WxMaTemplateMessage.Data("keyword3",paystate));
        tempData.add(new WxMaTemplateMessage.Data("keyword4",transeq));
        tempData.add(new WxMaTemplateMessage.Data("keyword5",stationname));
        tempData.add(new WxMaTemplateMessage.Data("keyword6","欢迎使用ITC不停车收费。如对订单有疑问，请在30分钟后联系客服！"));

        wxMaTemplateMessage.setToUser(openid);
        wxMaTemplateMessage.setTemplateId(templateId);
        wxMaTemplateMessage.setPage(page);
        wxMaTemplateMessage.setFormId(wxfromid);
        wxMaTemplateMessage.setEmphasisKeyword(emphasis_keyword);
        wxMaTemplateMessage.setColor(color);
        wxMaTemplateMessage.setData(tempData);


        /***********************************微信小程序配置***********************************/
        String WX_MINI_APPID = "wx3aeb995e0e36f951";
        String WX_MINI_APPP_SECRET = "23c09ee3a617ee9be73b8c2e827045f5";
        String WX_MINI_TOKEN = "wx3aeb995e0e36f951LILEI20190308";
        String WX_MINI_ENCODING_AESKEY = "GTbpHhf7kWVXyZ37HF6B9KHJZiyVcWVTv3CRnjTIITn";
        //初始化配置
        WxMaInMemoryConfig wxMaInMemoryConfig = new WxMaInMemoryConfig();
        wxMaInMemoryConfig.setAppid(WX_MINI_APPID);
        wxMaInMemoryConfig.setSecret(WX_MINI_APPP_SECRET);
        wxMaInMemoryConfig.setToken(WX_MINI_TOKEN);
        wxMaInMemoryConfig.setAesKey(WX_MINI_ENCODING_AESKEY);
        WxMaConfig wxMaConfig = wxMaInMemoryConfig;

        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(wxMaConfig);

        //发送支付订单
        try {
            wxMaService.getMsgService().sendTemplateMsg(wxMaTemplateMessage);
        } catch (WxErrorException e) {
            logger.error("推送小程序短信通知失败~~");
        }
    	return "";
    }


    public static void main(String[] args) throws ClientException, InterruptedException {

        //通行费扣款通知
        SendSmsResponse response = payTollNotice("18811658522","京A12345", "05月20日13时14分","八里桥收费站","10.00","1890.00");


        //进入收费站通知
        //SendSmsResponse response = inTollNotice("17521552527","京A12345","05月20日13时14分","八里桥收费站");

        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());

        Thread.sleep(3000L);

        //查明细
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = querySendDetails("13761031601",response.getBizId());
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
        }

    }
}
